package com.voxel.sense.infomsg.module.task.manager;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.com.common.app.BViewActivity;
import com.example.com.common.utils.NetworkUtils;
import com.example.com.common.view.EmptyView;
import com.example.com.common.view.recycler.RecyclerAdapter;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.voxel.sense.infomsg.R;
import com.voxel.sense.infomsg.data.bean.ConditionBean;
import com.voxel.sense.infomsg.interfaces.listener.onClickSubmitListener;
import com.voxel.sense.infomsg.module.task.TaskListAdapter;
import com.voxel.sense.infomsg.view.decoration.ItemDivider;
import com.voxel.sense.infomsg.view.decoration.LinearItemDecoration;
import com.voxel.sense.infomsg.view.dropmenu.DropDownMenu;
import com.voxel.sense.infomsg.view.titlebar.TextTitleBar;
import com.voxel.sense.infomsg.widget.adapter.FilterRecyclerAdapter;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cyy.example.com.facotry.constants.Constants;
import cyy.example.com.facotry.constants.EventBusConstants;
import cyy.example.com.facotry.model.EventEntity;
import cyy.example.com.facotry.model.api.response.MyTaskListInfoEntity;
import cyy.example.com.facotry.model.api.response.TaskStatuEntity;
import de.hdodenhof.circleimageview.CircleImageView;

/**
 * Created by ChenYiYao on 2017/11/20.
 * 任务主界面
 */

public class TaskManagerActivity extends BViewActivity<TaskManagerContract.Presenter> implements
        onClickSubmitListener, TaskManagerContract.View<TaskManagerContract.Presenter, MyTaskListInfoEntity> {
    @BindView(R.id.iv_send)
    CircleImageView iv_send;
    @BindView(R.id.tv_send)
    TextView tv_send;
    @BindView(R.id.ll_send)
    LinearLayout ll_send;//任务派发
    @BindView(R.id.iv_accept)
    CircleImageView iv_accept;
    @BindView(R.id.tv_accept)
    TextView tv_accept;
    @BindView(R.id.ll_accept)
    LinearLayout ll_accept;//任务接受
    @BindView(R.id.tv_acton)
    TextView tv_acton;
    @BindView(R.id.ll_action)
    LinearLayout ll_action;//任务执行
    @BindView(R.id.tv_check)
    TextView tv_check;
    @BindView(R.id.ll_check)
    LinearLayout ll_check;//任务审核
    @BindView(R.id.drop_down_menu)
    DropDownMenu drop_down_menu;
    @BindView(R.id.titlebar)
    TextTitleBar titlebar;


    private SmartRefreshLayout refresh_layout;//下拉刷新头
    private EmptyView empty_view;//占位的空界面布局
    private RecyclerView recycle_view;//任务列表
    private RecyclerView area_recycler;//地区筛选列表
    private RecyclerView type_recycler;//任务类型列表
    private RecyclerView mSmart_recycler;//只能筛选筛选列表

    private RecyclerAdapter mAdapter;//任务列表适配器
    private FilterRecyclerAdapter mAreaListAdapter;  //地区适配器
    private FilterRecyclerAdapter mTaskTypeAdapter; //行业类型适配器
    private FilterRecyclerAdapter mSmartAdapter; //行业类型适配器

    private List<View> popupViews = new ArrayList<>();//筛选栏目的集合
    private String headers[] = { "任务类型", "智能筛选"};
    private List<MyTaskListInfoEntity.BodyBean.TaskInfoListBean> mDatas;
    private String mCurrentCity;

    private boolean isFirstEnter = true;//是否首次进入

    public static void show(Context context) {
        context.startActivity(new Intent(context, TaskManagerActivity.class));
    }

    @Override
    protected int getContentLayoutId() {
        return R.layout.activity_task_manager;
    }

    @Override
    protected TaskManagerContract.Presenter initPresenter() {
        return new TaskManagerPresenter(this);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected boolean initArgs(Bundle bundle) {
        if (bundle != null) {
            mCurrentCity = bundle.getString(Constants.CURRENT_CITY);
        } else {
            mCurrentCity = Constants.DEFAULT_CITY;
        }
        return super.initArgs(bundle);
    }

    @Override
    protected void initData() {
        super.initData();
        titlebar.setTitleText("任务管理");
        initMenu();
        if (isFirstEnter) {
            refresh_layout.autoRefresh();//第一次进入触发自动刷新，演示效果
        }

        //初始化任务列表
        mAdapter = new TaskListAdapter();
        recycle_view.setLayoutManager(new LinearLayoutManager(this));
        recycle_view.addItemDecoration(new LinearItemDecoration(R.drawable.recycle_divider));
        recycle_view.setAdapter(mAdapter);

    }

    @Override
    protected void initEven() {
        super.initEven();
        refresh_layout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onRefresh(RefreshLayout refreshLayout) {
                handleRefresh();
            }

            @Override
            public void onLoadMore(RefreshLayout refreshLayout) {
                handleLoad();
            }
        });

        empty_view.addRefreshBtnEvent(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                empty_view.triggerOk();
                boolean b = refresh_layout.autoRefresh();
                //刷新过于频繁会导致失败，不会回调刷新方法
                if (!b) {
                    showEmptyView("",true);
                }
            }
        });
    }

    private void handleLoad() {
        if (NetworkUtils.isConnected()) {
            mPresenter.doLoadMoreData();
        } else {
            showEmptyView(getString(R.string.network_unavailable),true);
            refresh_layout.finishLoadMore();
        }
    }

    private void handleRefresh() {
        if (NetworkUtils.isConnected()) {
            //重新刷新，需要改变状态，可以加载更多数据
            refreshData();
        } else {
            refresh_layout.finishRefresh();
            showEmptyView(getString(R.string.network_unavailable),true);
        }
    }

    private void initMenu() {
        createAreaList();//创建地区筛选列表
        createTaskTypeList();//创建行业类型筛选列表
        createSmartList();//创建监管等级列表

        //将列表添加到菜单中
        //TODO:隐藏地区筛选条件
//        popupViews.add(area_recycler);
        popupViews.add(type_recycler);
        popupViews.add(mSmart_recycler);

        View view = LayoutInflater.from(this).inflate(R.layout.layout_recycler_emptty, null);
        refresh_layout = view.findViewById(R.id.refresh_layout);
        recycle_view = view.findViewById(R.id.recycle_view);
        empty_view = view.findViewById(R.id.empty_view);
        empty_view.bind(refresh_layout);
        //将主题列表添加入上级控件中
        drop_down_menu.setDropDownMenu(Arrays.asList(headers), popupViews, view);

    }

    private void createAreaList() {
        //地址选中列表
        area_recycler = new RecyclerView(this);
        area_recycler.setLayoutManager(new LinearLayoutManager(this));
        //设置下划线
        area_recycler.addItemDecoration(new LinearItemDecoration(R.drawable.recycle_divider));
        mAreaListAdapter = new FilterRecyclerAdapter(MenuListItemListener, Constants.TYPE_AREA);
        mAreaListAdapter.setHeadText("地区选中");
        mAreaListAdapter.setSubmitListener(this);
        area_recycler.setAdapter(mAreaListAdapter);
        mPresenter.doLoadRegionMenuData(mCurrentCity);
    }


    /**
     * 创建任务类型列表
     */
    private void createTaskTypeList() {
        //地址选中列表
        type_recycler = new RecyclerView(this);
        type_recycler.setLayoutManager(new LinearLayoutManager(this));
        //设置下划线
        type_recycler.addItemDecoration(new LinearItemDecoration(R.drawable.recycle_divider));
        //初始化适配器
        mTaskTypeAdapter = new FilterRecyclerAdapter(MenuListItemListener, Constants.TYPE_IDUSTRY);
        mTaskTypeAdapter.setHeadText("全类型");
        type_recycler.setAdapter(mTaskTypeAdapter);
        mTaskTypeAdapter.setSubmitListener(this);
        mPresenter.doLoadTaskTypeMenuData();
    }


    /**
     * 创建智能筛选类型列表
     */
    private void createSmartList() {
        //地址选中列表
        mSmart_recycler = new RecyclerView(this);
        mSmart_recycler.setLayoutManager(new LinearLayoutManager(this));
        //设置下划线
//        mSuperviseRecylerItemDivider = new SuperviseRecylerItemDivider(R.drawable.recycle_divider,
//                R.drawable.recycle_supervise_tip_divider);
        mSmart_recycler.addItemDecoration(new LinearItemDecoration(R.drawable.recycle_divider));
        //创建适配器
        mSmartAdapter = new FilterRecyclerAdapter(MenuListItemListener, Constants.Type_Smart);
        mSmartAdapter.setSingleSelect(true);
        mSmartAdapter.setHeadText("全类型");
        mSmart_recycler.setAdapter(mSmartAdapter);
        mSmartAdapter.setSubmitListener(this);
        mPresenter.doLoadOtherMenuData();
    }


    /**
     * 菜单列表item点击监听
     */
    RecyclerAdapter.AdapterListenerImpl MenuListItemListener = new RecyclerAdapter.AdapterListenerImpl<ConditionBean>() {
        @Override
        public void onItemClick(RecyclerAdapter.ViewHolder holder, ConditionBean bean) {
            super.onItemClick(holder, bean);
            if (bean == null)
                return;
            mPresenter.changeSearchCondition(bean);
        }
    };


    @OnClick({R.id.ll_send, R.id.ll_accept, R.id.ll_action, R.id.ll_check})
    public void onViewClicked(View view) {
        switch (view.getId()) {
//            case R.id.ll_send://任务派送
//                SendTaskActivity.show(this);
//                break;
//            case R.id.ll_accept://任务接收
//                TaskOperationActivity.show(this, Constants.TASK_UNACCEPT_TYPE, Constants.DEFAULT_CITY);
//                break;
//            case R.id.ll_action://任务执行
//                TaskOperationActivity.show(this, Constants.TASK_ACTION_TYPE, Constants.DEFAULT_CITY);
////                MissionDescribeActivity.show(this);
//                break;
//            case R.id.ll_check://任务审核
//                TaskOperationActivity.show(this, Constants.TASK_FINISH_TYPE, Constants.DEFAULT_CITY);
//                break;
        }
    }

    //菜单筛选栏列表提交按钮
    @Override
    public void onSubmit(List list, String type) {
        drop_down_menu.closeMenu();
        mPresenter.doSubmitSearchCondition();
        refresh_layout.autoRefresh();
    }

    private void refreshData() {
        refresh_layout.setNoMoreData(false);
        mPresenter.doLoadData();
    }

    @Subscribe
    public void onEvnetBus(EventEntity event) {
        if (event == null) {
            return;
        }
        if (EventBusConstants.CHANGE_TASK_STATUS_SUCCESS.equals(event.key)) {
            //接收到任务状态改变的消息，若列表包含该任务，则也需要同步更新
            TaskStatuEntity entity = (TaskStatuEntity) event.value;
            String taskNumber = entity.getBody().getTaskNumber();
            String taskStatus = entity.getBody().getTaskStatus();
            if (!TextUtils.isEmpty(taskNumber) && TextUtils.isEmpty(taskStatus)) {
                for (MyTaskListInfoEntity.BodyBean.TaskInfoListBean bean : mDatas) {
                    if (taskNumber.equals(bean.getTaskNumber())) {
                        bean.setTaskStatus(taskStatus);
                        mAdapter.notifyDataSetChanged();
                        return;
                    }
                }
            }
        } else if (EventBusConstants.CHECK_TASK_PASS.equals(event.key)) {
            //任务审核通过消息通知
            String num = (String) event.value;
            taskCheckMsg(num, "3");
        } else if (EventBusConstants.CHECK_TASK_NO_PASS.equals(event.key)) {
            String num = (String) event.value;
            taskCheckMsg(num, "0");
        } else if (EventBusConstants.TASK_ACTION_FINISH.equals(event.key)) {
            //接到执行完成通知
            String num = (String) event.value;
            taskCheckMsg(num, "2");
        }
    }

    private void taskCheckMsg(String num, String statu) {
        //TODO:
        List items = mAdapter.getItems();
        for (int i = 0; i < items.size(); i++) {
            MyTaskListInfoEntity.BodyBean.TaskInfoListBean bean = (MyTaskListInfoEntity.BodyBean.TaskInfoListBean) items.get(i);
            if (bean.getTaskNumber().equals(num)) {
                bean.setTaskStatusId(statu);
                mAdapter.notifyDataSetChanged();
                return;
            }
        }
    }

    @Override
    public RecyclerAdapter<MyTaskListInfoEntity> getRecyclerViewAdapter() {
        return mAdapter;
    }

    @Override
    public void onAdapterDataChanged() {
        empty_view.triggerOkOrEmpty(mAdapter.getItemCount() > 0 ? true : false);
    }

    @Override
    public void showEmptyView(String desc, boolean btnVisible) {
        boolean b = mAdapter.getItemCount() > 0;
        empty_view.setRefreshBtnVisible(btnVisible);
        if (!b && !TextUtils.isEmpty(desc)) {
            empty_view.triggerError(desc);
        } else if (b) {
            //发生错误，列表有数据，不能显示空界面
            super.showError(desc);
        } else if (!NetworkUtils.isConnected()) {
            empty_view.triggerNetError();
        } else {
            empty_view.triggerEmpty();
        }
    }

    @Override
    public void onShowNoMore(boolean b) {
        refresh_layout.setNoMoreData(b);
    }

    @Override
    public void onRefreshFinish() {
        if (isFirstEnter) {
            isFirstEnter = false;
        }
        refresh_layout.finishRefresh();
        empty_view.triggerOkOrEmpty(mAdapter.getItemCount() > 0 ? true : false);
    }

    @Override
    public void onLoadMoreFinish() {
        refresh_layout.finishLoadMore();
    }

    @Override
    public void onNotifyRegionData(List<ConditionBean> datas) {
        mAreaListAdapter.replace(datas);
    }

    @Override
    public void onNotifyTaskTypeData(List<ConditionBean> datas) {
        mTaskTypeAdapter.replace(datas);
    }

    @Override
    public void onNotifyOtherData(List<ConditionBean> datas) {
        mSmartAdapter.replace(datas);
    }
}
